<?php
namespace app\admin\controller;

use app\admin\model\AdminRole as AdminRoleModel;
use app\admin\model\Permission;
use app\common\utils\Jwt;
use app\common\utils\Token;
use app\common\exception\AdminException;
use app\admin\model\Admin as AdminModel;
use app\admin\validate\Auth as AuthValidate;
use app\common\utils\TreeUtil;

class Auth extends Base
{
    protected function _initialize()
    {
        //如果要检测token,就调用父类_initialize方法
//        parent::_initialize();
    }

    public function login()
    {
        (new AuthValidate())->goCheck();
        $username = request()->post('username');
        $password = request()->post('password');
        $password = md5($password);
        $admin = AdminModel::with(['roles','roles.permissions'])->find(function ($query) use ($username, $password) {
            $query->where(['username' => $username, 'password' => $password, 'status' => 1]);
        });

        if (empty($admin)) {
            throw new AdminException(['msg'=>'用户不存在', 'http_code'=>200]);
        }

        $admin->role = 1;
        $permission = TreeUtil::listToTreeMulti(Permission::all(), 0, 'id', 'pid', 'children');

        $jwt = new Jwt();
        $data = [
            'id'=>$admin->id,
            'username' => $admin->username,
            'token' => $jwt->generateToken($admin->id),
        ];
        return $this->ok($data);
    }

    public function menu()
    {
        //check token of header
        parent::_initialize();
        $admin_id = self::$admin || 1;
        //return menu
        $permission = TreeUtil::listToTreeMulti(Permission::all(), 0, 'id', 'pid', 'children');
        return $this->ok(parseTree($permission));
    }

    public function info()
    {
//        parent::_initialize();
        $admin_id = self::$admin || 1;

        $admin = AdminModel::with('rol')->find(function ($query) use ($admin_id) {
            $query->where(['id' => $admin_id, 'status' => 1]);
        });
        // echo "<pre>";
        // print_r($admin);die;
        return $this->ok($admin);
    }

    public function logout()
    {
        //如果要检测token,就调用父类_initialize方法
//        parent::_initialize();

        $token = Token::getBearToken();
        $delete_token = cache('delete_token')?:[];
        $delete_token[]=$token;
        //缓存一天
        cache('delete_token', $delete_token, config('setting.jwt_expire_in'));
        $this->ok([], '退出成功');
    }
}